package com.yu.crm.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.yu.crm.domain.pojo.AttendanceSet;
import com.yu.crm.domain.pojo.CrmDepartmentMember;
import com.yu.crm.domain.pojo.SetInfo;
import com.yu.crm.mapper.AttendanceSetMapper;
import com.yu.crm.service.CrmDepartmentMemberService;
import com.yu.crm.service.CrmDepartmentService;
import com.yxzz.common.config.UserCacheManager;
import com.yxzz.common.exception.GeneralException;
import com.yxzz.common.helper.DataHelpers;
import lombok.Data;
import lombok.extern.log4j.Log4j2;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.dao.DuplicateKeyException;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.List;

/**
 * <p>
 * 考勤设置表 服务实现类
 * </p>
 *
 * @author ct
 * @since 2019-12-31
 */
@Service
@Log4j2
@Transactional(rollbackFor = Exception.class)
public class AttendanceSetService extends ServiceImpl<AttendanceSetMapper, AttendanceSet>{
    @Autowired
    UserCacheManager userCacheManager;
    @Autowired
    CrmDepartmentMemberService crmDepartmentMemberService;
    @Autowired
    CrmDepartmentService crmDepartmentService;
    @Autowired
    AttendanceRecordService attendanceRecordService;

    /**
     * 新增或修改考勤设置表
     * @param attendanceSet
     * @return
     */
    public Long addOrUpdate(AttendanceSet attendanceSet){
        if (DataHelpers.isEmptyString(attendanceSet.getDepartmentId())) {
            throw new GeneralException("部门id不能为空");
        }
        Long departmentId = Long.parseLong(attendanceSet.getDepartmentId());
        List<Long> longList = new ArrayList<>();
        longList.add(departmentId);
        //考勤设置可能设置的是父部门  判断该用户是否已经被设置
        List<Long> pidList = crmDepartmentService.getPid(departmentId, longList);
        SetInfo setInfo = new SetInfo();
        setInfo.setList(pidList);
        AttendanceSet set = this.listByDepId(setInfo);
        if (DataHelpers.isNotEmpty(set)) {
            throw new GeneralException("该部门或者父部门已经设置，不能重复设置");
        }
        String userId=userCacheManager.getCurrentUser().getUserId();
        if(DataHelpers.isNotEmpty(attendanceSet.getId())){
            attendanceSet.setGmtModified(LocalDateTime.now());
        }else{
            attendanceSet.setUserId(userId);
            attendanceSet.setGmtCreate(LocalDateTime.now());
            attendanceSet.setGmtModified(LocalDateTime.now());
        }
        try {
            if(saveOrUpdate(attendanceSet)){
                Long id = attendanceSet.getId();
                if(DataHelpers.isNotEmpty(id)){
                    log.info("新增或修改考勤设置表成功");
                    return id;
                }
            }
        }catch (DuplicateKeyException e){
            e.printStackTrace();
            log.error("当前部门已有考勤日期");
            throw new GeneralException("当前部门已有考勤日期");
        }catch (Exception e){
            e.printStackTrace();
            log.error("新增或修改考勤设置表失败");
            throw new GeneralException("新增或修改考勤设置表失败");
        }
        return null;
    }

    private AttendanceSet listByDepId(SetInfo setInfo) {
        List<AttendanceSet> list = baseMapper.ListByDepId(setInfo);
        if (DataHelpers.isNotEmpty(list) && list.size()>0) {
            return list.get(list.size()-1);
        }else {
            return null;
        }
    }


    /**
     * 通过id软删除数据
     * @param id
     * @return
     */
    public Boolean deleteById(Long id){
        AttendanceSet attendanceSet=new AttendanceSet();
        attendanceSet.setIsDeleted(1);

        QueryWrapper<AttendanceSet> queryWrapper=new QueryWrapper<>();
        queryWrapper.eq("id",id);
        queryWrapper.eq("is_deleted",0);

        try {
            baseMapper.update(attendanceSet, queryWrapper);
            log.info("删除考勤设置表成功");
        }catch (Exception e){
            e.printStackTrace();
            log.error("删除考勤设置表失败");
            throw new GeneralException("删除考勤设置表失败");
        }
        return true;
    }

    /**
     * 通过id查询考勤设置详情
     * @param id
     * @return
     */
    public AttendanceSet infoById(Long id){
        try {
            AttendanceSet attendanceSet = baseMapper.selectById(id);
            log.info("通过考勤编号查询考勤设置表详情成功");
            return attendanceSet;
        }catch (Exception e){
            e.printStackTrace();
            log.error("通过考勤编号查询考勤设置表详情失败");
            throw new GeneralException("通过考勤编号查询考勤设置表详情失败");
        }
    }

    /**
     * 通过用户id查询考勤设置详情
     * @param userId
     * @return
     */
    public AttendanceSet infoByUserId(String userId){
        //获取到当前部门
        CrmDepartmentMember member = crmDepartmentMemberService.infoByUserId(userId);
        if(DataHelpers.isEmpty(member)){
            throw new GeneralException("此用户有误");
        }
        try {
            List<Long> longList = new ArrayList<>();
            longList.add(member.getDepartmentId());
            //考勤设置可能设置的是父部门  判断该用户是否已经被设置
            List<Long> pidList = crmDepartmentService.getPid(member.getDepartmentId(), longList);
            SetInfo setInfo = new SetInfo();
            setInfo.setList(pidList);
            AttendanceSet attendanceSet = this.listByDepId(setInfo);
            if(DataHelpers.isNotEmpty(attendanceSet)){
                log.info("通过用户编号查询考勤设置表详情成功");
            }
            return attendanceSet;
        }catch (Exception e){
            e.printStackTrace();
            log.error("通过用户编号查询考勤设置表详情失败");
            throw new GeneralException("通过用户编号查询考勤设置表详情失败");
        }
    }


    /**
     * 通过条件查询考勤设置数据
     * @param page
     * @param condition
     * @return
     */
    public IPage<AttendanceSet> attendanceSetIPage(Page<AttendanceSet> page, String condition) {
       /* QueryWrapper<AttendanceSet> queryWrapper=new QueryWrapper<>();
        queryWrapper.eq("is_deleted",0);*/
        try {
            //IPage<AttendanceSet> attendanceSetIPage = baseMapper.selectPage(page, queryWrapper);
            IPage<AttendanceSet> attendanceSetIPage = baseMapper.ipage(page,condition);
            if(DataHelpers.isNotEmpty(attendanceSetIPage.getRecords())){
                log.info("通过条件查询考勤设置数据成功");
            }
            return attendanceSetIPage;
        }catch (Exception e){
            e.printStackTrace();
            log.error("通过条件查询考勤设置数据失败");
            throw new GeneralException("通过条件查询考勤设置数据失败");
        }
    }


}
